package panels;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.Document;

import recipe.ShopListFormatter;
import beans.Recipe;
import util.PrintItem;

/**
 * 
 */
public class ShopListPanel extends JPanel implements ActionListener{

	private JTextPane shopList;
	private JScrollPane shopListScroller;
    private JButton pButton;
    private JPanel shopPanel;
    private Document shopListDoc = null;
    private Object printObject[] = null;
	
    /**
     * 
     */
	public ShopListPanel() {
        shopList = new JTextPane();
		shopListScroller = new JScrollPane(shopList);
		shopListScroller.setPreferredSize(new Dimension(400,500));
		
        pButton = new JButton("Tulosta");
        pButton.addActionListener(this);
        
        shopPanel = new JPanel(new BorderLayout());
        shopPanel.add(shopListScroller, BorderLayout.CENTER);
        shopPanel.add(pButton, BorderLayout.SOUTH);
        
        add(shopPanel);
	}

    /**
     * 
     * @param Document doc
     */
	public void setShopList(Document doc){
		shopList.setDocument(doc);
	}
	
    /**
     * 
     * @return Document
     */
	public Document getShopList(){
		return shopList.getDocument();
	}

    /**
     * 
     * @param Recipe recipe
     */
	public void appendToShopList(Recipe recipe){
		shopList.setStyledDocument(ShopListFormatter.formatShopList(recipe,shopList.getStyledDocument()));
	}
    
    /**
     * 
     */
    public void actionPerformed(ActionEvent e) {
        System.out.println("actionPerformed on print button");
        
        shopListDoc = shopList.getDocument();
        if(shopListDoc != null) {
            PrintItem pItem = new PrintItem(shopListDoc);
            
            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setPrintable(pItem);
    
            // Page dialog
            PageFormat pf = printJob.pageDialog(printJob.defaultPage());
    
            // Print dialog
            if(printJob.printDialog()){
                try { 
                    printJob.print(); 
                } catch (Exception PrintException) {}
            }
        }
    }
}
